package com.kevin.design.creationalPattern.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
// 静态内部类 IoDH
public class IoDHOfLoadBalancer {
    public static void main(String[] args) {
        LoadBalancer instance1 = LoadBalancerIoDH.getInstance();
        LoadBalancer instance2 = LoadBalancerIoDH.getInstance();
        if (instance1 == instance2){
            System.out.println("负载均衡器是唯一的");
        }
        instance1.addServer("server1");
        instance2.addServer("server2");
        for (int i=0;i<10;i++){
            System.out.println("服务器：" + instance1.getServer());
        }
    }
}

class LoadBalancerIoDH implements LoadBalancer{

    private List<String> serverList;

    private LoadBalancerIoDH(){
        serverList = new ArrayList<>();
    }

    private static class IoDH{
        private final static LoadBalancer instance = new LoadBalancerIoDH();
    }
    public static LoadBalancer getInstance(){
        return IoDH.instance;
    }
    @Override
    public void addServer(String server) {
        serverList.add(server);
    }

    @Override
    public void removeServer(String server) {
        serverList.remove(server);
    }

    @Override
    public String getServer() {
        Random random = new Random();
        int i = random.nextInt(serverList.size());
        return serverList.get(i);
    }
}
